package com.token.sysflow.core;

import com.alibaba.fastjson.JSONObject;
import com.token.sql.IntegrateSql;
import com.token.sysflow.exception.ErrorCodeEnum;
import com.token.sysflow.exception.FlowException;
import com.token.sysflow.hander.ApproveProcess;
import com.token.sysflow.impl.AbstractFlowHandlerImpl;
import com.token.sysflow.impl.SubmitFlowImpl;

/**
 * 会签提交
 *
 * @author chenjianxiong 2020/4/13
 */
public class SubmitHQ extends SubmitFlow {
    /**
     * @param f
     * @param process
     * @throws Exception
     */
    public SubmitHQ(IntegrateSql f, ApproveProcess process) throws Exception {
        super(f, process);
    }

    @Override
    public void execute(AbstractFlowHandlerImpl flowHandler) throws Exception {
        submitFlow = (SubmitFlowImpl) flowHandler;

        //初始化起草人、申请人、当前人。
        initUserInfo(approveProcess.getCreater(),approveProcess.getApplyer(),submitFlow.getActionUser());

        synchronized (SubmitHQ.class) {
            System.out.println(">>>开始锁定 = " + flowHandler.getActionUser());
            submitFlowHandlerBefore();
            long num = approveProcess.getStepApprovesNum();
            if (num == 0) {
                //设置目标流程
                super.setToFlowById(approveProcess.getFlowId());

                //设置目标环节
                JSONObject jsonObject  = submitFlow.getFieldValues();
                if(jsonObject == null){
                    jsonObject = new JSONObject();
                }
                jsonObject.putAll(this.getUserInfoMap());
                super.setToStep(this.getFromStep().getDefaultNextStep(jsonObject));

                //计算出目标办理人
                super.executeDefaultApprover();

                //根据环节类型来提交。
                super.submitByToStepType(submitFlow.getActionUser());

                //生成知会记录
                super.handleNotification(submitFlow.getActionUser(),submitFlow.getSelectApprover(),submitFlow.getFieldValues());

            } else if (num > 0) {//大于一个办理人时。
//                super.setToFlow(super.getFromFlow());
//                super.setToStep(super.getFromStep());

                //添加输出参数
                approveProcess.appendFlowProcessInfo(fromFlow, fromStep);
            } else { //其它
                throw new FlowException(ErrorCodeEnum.TASK_APPROVER);
            }

            //生成新的流转记录和办理意见
            super.createFlowApproveLog(flowHandler);
            System.out.println(">>>结束锁定 = " + flowHandler.getActionUser());
//        }
        }
    }

}
